#include <iostream>
#include <filesystem>
#include "dataManager.h"
#include "serverConfig.h"
#include "userManager.h"

namespace fs = std::filesystem;
using namespace std;

DataManager::DataManager()
{
    // 检查数据文件目录是否存在
    string dp = CFGAPP->dataPath();
    if (!fs::exists(dp)) {
        fs::create_directories(dp);
        std::cout << "Directory created: " << dp << std::endl;
    }

    // 检查用户数据文件
}

DataManager::~DataManager()
{
}

void DataManager::userRegisterThread(Json obj)
{
    string user     = obj.value("user", "");
    string passwd   = obj.value("passwd", "");
    string phone    = obj.value("phone", "");
    string email    = obj.value("email", "");
    cout << "userRegisterThread>>>> " << obj << endl;
    // 1. 查找是否存在相同用户
    if(UAPP->isUserExists(user)) {
        return;
    }

    cout << "userRegisterThread>>>> " << obj << endl;
    UserInfo d;
    memset(&d, 0, sizeof(d));
    // 2. 生成 id
    d.id = UAPP->lastUserId() + 1;
    memcpy(d.user,      user.c_str(),   user.size());
    memcpy(d.passwd,    passwd.c_str(), passwd.size());
    memcpy(d.phone,     phone.c_str(),  phone.size());
    memcpy(d.email,     email.c_str(),  email.size());

    // 3. 保存用户信息
    UAPP->addUser(d);
}

bool DataManager::handle(const ClientDataMessage *pMsg)
{
    switch (pMsg->type)
    {
    case CDT_LOGIN:
    {
        break;
    }
    case CDT_REGISTER:
    {
        thread t(&DataManager::userRegisterThread, this, pMsg->data);
        t.detach();
        break;
    }
    
    default:
        break;
    }
}